package org.demo.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 广播 Server
 * ip: a.b.c.d
 * A 类地址：a < 128       , b.c.d 表示主机地址
 * B 类地址：128 <= a < 192, a.b 表示网络地址, c.d 表示主机地址
 * C 类地址：192 <= a      , a.b.c 表示网络地址, d 表示主机地址
 * D 类地址：224.0.0.0 ~ 239.255.255.255 保留地址 [广播地址的有效范围]
 * @author  
 * @date    2010-9-6
 * @file    org.demo.net.BroadCastServer.java
 */
public class BroadCastServer {
	// group ip
	private static String ip = "224.0.0.0";
	// group port
	private static int port = 7777;
	// group
	private InetAddress group = null;
	
	// socket
	private MulticastSocket socket = null;
	private static int timeToLive = 2;
	// 数据包大小
	private static int length = 1024;
	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		BroadCastServer server = new BroadCastServer();
		
		// 加入到广播组中
		server.joinGroup();
		// 发送消息
		for (int i=0; i<22; i++){
			server.sendMessage("广播消息..." + i);
			Thread.sleep(1000);
		}
	}
	/**
	 * 构造函数
	 * @throws IOException
	 */
	public BroadCastServer()throws IOException{
		// 创建广播组
		this.group = InetAddress.getByName(ip);
	}
	/**
	 * 加入到广播组中
	 */
	public void joinGroup()throws IOException{
		this.socket = new MulticastSocket(port);
		this.socket.setTimeToLive(timeToLive);
		this.socket.joinGroup(group);
	}
	/**
	 * 发送数据
	 * @param data
	 * @throws IOException
	 */
	public void sendMessage(String data)throws IOException{
		// 创建数据包
		DatagramPacket packet = createDataPack(data);
		// 发送数据包
		this.socket.send(packet);
	}
	/**
	 * 接收数据
	 * @return
	 * @throws IOException
	 */
	public String receiveMessage()throws IOException{
		// 创建数据包
		DatagramPacket pack = createDataPack(length);
		// 接收数据,会发生阻塞
		socket.receive(pack);
		
		// 接收到的数据
		byte[] data = pack.getData();
		// 接收到的数据长度
		int size = pack.getLength();
		return new String(data,0,size);
	}
	/**
	 * 构造发送数据包
	 * @param host
	 * @param port
	 * @param data
	 * @return
	 */
	public DatagramPacket createDataPack(String data){
		DatagramPacket pack = null;
		try {
			byte[] buf = data.getBytes();
			pack = new DatagramPacket(buf,buf.length,group,port);
		} catch(Exception e){
			throw new RuntimeException(e);
		}
		return pack;
	}
	/**
	 * 构造接收数据包
	 * @param length
	 * @return
	 */
	public DatagramPacket createDataPack(int length){
		byte[] buf = new byte[length];
		DatagramPacket pack = new DatagramPacket(buf,length,group,port);
		return pack;
	}
}
